package com.zqxq.lottery.service.news.impl;

import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.zqxq.common.constant.Result;
import com.zqxq.common.enums.CodeEnum;
import com.zqxq.common.utils.StrUtils;
import com.zqxq.lottery.config.YmlConfig;
import com.zqxq.lottery.entity.po.news.MatchNewsLikesPO;
import com.zqxq.lottery.entity.po.news.MatchNewsPO;
import com.zqxq.lottery.entity.po.user.UserCashPO;
import com.zqxq.lottery.entity.po.user.UserFundsPO;
import com.zqxq.lottery.entity.po.user.UserInfoPO;
import com.zqxq.lottery.entity.vo.news.MatchNewsLikesVO;
import com.zqxq.lottery.entity.vo.news.MatchNewsVO;
import com.zqxq.lottery.mapper.news.MatchNewsLikesMapper;
import com.zqxq.lottery.mapper.news.MatchNewsMapper;
import com.zqxq.lottery.mapper.user.UserCashMapper;
import com.zqxq.lottery.mapper.user.UserFundsMapper;
import com.zqxq.lottery.mapper.user.UserInfoMapper;
import com.zqxq.lottery.service.news.IMatchNewsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * @author 苦智
 * @date 2018/9/5 10:36
 * @description 资讯
 * @ClassName MatchNewsServiceImpl
 */
@Service
@Slf4j
public class MatchNewsServiceImpl extends ServiceImpl<MatchNewsMapper,MatchNewsPO> implements IMatchNewsService {
    @Autowired
    private MatchNewsLikesMapper matchNewsLikesMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private UserFundsMapper userFundsMapper;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private YmlConfig ymlConfig;
    @Autowired
    private UserCashMapper userCashMapper;

    @Override
    public Page<MatchNewsVO> selectPageByType(Integer type, Integer pageNo, Integer pageSize) {
        Page<MatchNewsVO> page = new Page<>(pageNo,pageSize);
        List<MatchNewsVO> l = baseMapper.selectPageByType(page,type);
        page.setRecords(l);
        return page;
    }

    @Override
    public MatchNewsLikesPO saveNewsLikes(String newsId, String userId,String payAmount) {
        MatchNewsLikesPO matchNewsLikesPO = new MatchNewsLikesPO();
        matchNewsLikesPO.setUser_id(Long.valueOf(userId));
        matchNewsLikesPO.setNews_id(Long.valueOf(newsId));
        matchNewsLikesPO.setPay_amount(new BigDecimal(payAmount));
        matchNewsLikesPO.setStatus(0);
        matchNewsLikesMapper.insert(matchNewsLikesPO);
        MatchNewsLikesPO newsLikesPO = matchNewsLikesMapper.selectOne(matchNewsLikesPO);
        return newsLikesPO;
    }

    @Override
    public Result payReward(MatchNewsLikesVO vo) {
        Result result = new Result();
        MatchNewsLikesPO po = matchNewsLikesMapper.selectById(vo.getLikesId());
        if (po == null ||!vo.getUserId().equals(po.getUser_id().toString())){
            result.setCode(CodeEnum.FAIL.getCode());
            result.setMsg("用户id与订单用户信息不一致");
            return result;
        }
        if(po.getStatus()==2){
            return new Result(CodeEnum.FAIL.getCode(), "您的打赏已支付！");
        }
        if (new BigDecimal(vo.getPayAmount()).compareTo(po.getPay_amount()) != 0){
            result.setCode(CodeEnum.FAIL.getCode());
            result.setMsg("打赏金额与订单信息不一致");
            return result;
        }
        if (po.getPay_amount() == null || po.getPay_amount().doubleValue() <=0 ){
            result.setCode(CodeEnum.FAIL.getCode());
            result.setMsg("订单金额有误");
            return result;
        }
        String key = "PAY_REWARD_"+vo.getLikesId();
        String value = stringRedisTemplate.opsForValue().get(key);
        if(StrUtils.isNotEmpty(value)){
            return new Result(CodeEnum.FAIL.getCode(), "您还有未处理的支付订单，请稍后操作！");
        }
        try{
            stringRedisTemplate.opsForValue().set(key, key);
            Map<String, Object> userFundsMap = userFundsMapper.getById(Long.valueOf(vo.getUserId()));
            BigDecimal balance = (BigDecimal) userFundsMap.get("balance");  //中奖趣豆
            BigDecimal lotBean = (BigDecimal) userFundsMap.get("lotBean");  //签到领奖趣豆
            BigDecimal bonus = (BigDecimal) userFundsMap.get("bonus");  //充值趣豆
            BigDecimal subTotal = balance.add(lotBean).add(bonus);  //总余额
            BigDecimal payAmount = po.getPay_amount(); //订单金额
            if (subTotal.compareTo(payAmount) == -1) {
                return new Result(10003, "余额不足，请充值！");
            }
            Long userId = Long.valueOf(vo.getUserId());
            Long likesId = Long.valueOf(vo.getLikesId());
            UserInfoPO userInfoPO = userInfoMapper.selectById(userId);
            BigDecimal money = lotBeanConsume(userInfoPO, payAmount);    //平台赠送趣豆消费
            if (money.compareTo(BigDecimal.ZERO) == 1) {
                BigDecimal _money = bonusConsume(userInfoPO, money);    //充值趣豆消费
                if (_money.compareTo(BigDecimal.ZERO) == 1) {
                    balanceConsume(userInfoPO, _money); //中奖趣豆消费
                }
            }
            UserCashPO userCashPO = new UserCashPO();
            userCashPO.setId(ymlConfig.getPkId());
            userCashPO.setUser_id(userInfoPO.getId());
            userCashPO.setReal_name(userInfoPO.getReal_name());
            userCashPO.setMobile(userInfoPO.getMobile());
            userCashPO.setPay_way(3);
            userCashPO.setPay_account(likesId + "");
            userCashPO.setType(12);
            userCashPO.setStatus(4);
            userCashPO.setPay_amount(payAmount);
            userCashPO.setRemainder(subTotal.subtract(payAmount));
            userCashMapper.insert(userCashPO);
            //修改订单状态  余额购买
            updateNewsStatus(userId, likesId, 2);
            result.setData(vo);
        }catch(Exception e){
            log.error(vo.getLikesId()+"支付失败",e);
        }finally {
            stringRedisTemplate.delete(key);
        }
        return result;
    }

    private boolean updateNewsStatus(Long userId, Long likesId, int status) {
        MatchNewsLikesPO matchNewsLikesPO = new MatchNewsLikesPO();
        matchNewsLikesPO.setId(likesId);
        matchNewsLikesPO.setStatus(status);
        Integer c = matchNewsLikesMapper.updateById(matchNewsLikesPO);
        if (c>0){
            return true;
        }
        return false;
    }

    /**
     * 平台赠送趣豆消费
     */
    private BigDecimal lotBeanConsume(UserInfoPO userInfo, BigDecimal money){
        UserFundsPO userFundsPO = userFundsMapper.selectById(userInfo.getId());
        if (null != userFundsPO && userFundsPO.getLot_bean().intValue()>0){
            if(money.compareTo(userFundsPO.getLot_bean().setScale(2,BigDecimal.ROUND_DOWN))>0){
                money = money.subtract(userFundsPO.getLot_bean());
                userFundsPO.setLot_bean(new BigDecimal(0));
            }else{
                userFundsPO.setLot_bean(userFundsPO.getLot_bean().subtract(money));
                money = new BigDecimal(0);
            }
            userFundsPO.setConsume_status(1);
            userFundsMapper.updateById(userFundsPO);
        }
        return money;
    }
    /**
     * 充值趣豆消费
     */
    private BigDecimal bonusConsume(UserInfoPO userInfo, BigDecimal money){
        UserFundsPO userFundsPO = userFundsMapper.selectById(userInfo.getId());
        if (null != userFundsPO && userFundsPO.getBonus().intValue()>0){
            if(money.compareTo(userFundsPO.getBonus().setScale(2,BigDecimal.ROUND_DOWN))>0){
                money = money.subtract(userFundsPO.getBonus());
                userFundsPO.setBonus(new BigDecimal(0));
            }else{
                userFundsPO.setBonus(userFundsPO.getBonus().subtract(money));
                money = new BigDecimal(0);
            }
            userFundsPO.setConsume_status(1);
            userFundsMapper.updateById(userFundsPO);
        }
        return money;
    }

    /**
     * 中奖趣豆消费
     */
    private BigDecimal balanceConsume(UserInfoPO userInfo, BigDecimal money){
        UserFundsPO userFundsPO = userFundsMapper.selectById(userInfo.getId());
        if (null != userFundsPO && userFundsPO.getBalance().intValue()>0){
            if(money.compareTo(userFundsPO.getBalance().setScale(2,BigDecimal.ROUND_DOWN))>0){
                money = money.subtract(userFundsPO.getBalance());
                userFundsPO.setBalance(new BigDecimal(0));
            }else{
                userFundsPO.setBalance(userFundsPO.getBalance().subtract(money));
                money = new BigDecimal(0);
            }
            userFundsPO.setConsume_status(1);
            userFundsMapper.updateById(userFundsPO);
        }
        return money;
    }
}
